package com.infogant.web.resouces;

/**
 * Created by peter.henell on 19/02/15.
 */

import com.codahale.metrics.annotation.Timed;
import com.google.common.base.Optional;
import com.infogant.dao.core.AbstractPersonDAO;
import com.infogant.dao.core.PersonDAO;
import com.infogant.dto.Person;
import com.infogant.web.Saying;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import java.util.concurrent.atomic.AtomicInteger;

@Path("/add-user")
@Produces(MediaType.APPLICATION_JSON)
public class AddUserResource {
    private final String template;
    private final String defaultName;
    private final AtomicInteger counter;

    private final AbstractPersonDAO dao;

    public AddUserResource(String template, String defaultName, AbstractPersonDAO dao) {
        this.dao = dao;
        this.template = template;
        this.defaultName = defaultName;
        this.counter = new AtomicInteger();
    }


    @GET
    @Timed
    public Saying addUser(@QueryParam("name") Optional<String> name) throws Exception {
        Person person = new Person();
        person.setName(name.or(defaultName));
        person.setId(counter.incrementAndGet());

        dao.twoPersons(person, person);


        final String value = String.format(template, name.or(defaultName));
        return new Saying(person.getId(), value);
    }
}